<template>
  <div class="carbon-assets-container">
    <div class="sidebare">
      <div class="sidebar">
        <a-menu
          v-model:selectedKeys="state.selectedKeys"
          mode="inline"
          :open-keys="state.openKeys"
          :items="items"
          @openChange="onOpenChange"
        ></a-menu>
      </div>
    </div>

    <a-card title="碳资产列表" class="card">
      <a-button type="primary" @click="addCarbonAsset" class="add-button"> 增加碳资产 </a-button>
      <a-table
        :dataSource="carbonAssets"
        :columns="columns"
        rowKey="name"
        @change="handleChange"
        class="carbon-assets-table"
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span class="action-buttons">
              <a @click="editCarbonAsset(record)" class="edit-button">编辑</a>
              <a-divider type="vertical" />
              <a @click="deleteCarbonAsset(record)" class="delete-button">删除</a>
            </span>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:open="isModalVisible" title="碳资产" @cancel="handleCancel" @ok="saveCarbonAsset">
      <a-form :model="currentAsset" layout="vertical">
        <a-form-item label="碳资产名称">
          <a-input v-model:value="currentAsset.assetName" />
        </a-form-item>
        <a-form-item label="碳资产类别">
          <a-select
            v-model:value="currentAsset.assetCategoryId"
            style="width: 100%"
            :fieldNames="{ label: 'caCategoryName', value: 'caCategoryId' }"
            :options="assetsCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="GHG Protocol 范围">
          <a-select
            v-model:value="currentAsset.ghgId"
            style="width: 100%"
            :fieldNames="{ label: 'ghgName', value: 'ghgId' }"
            :options="ghgCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="ISO 14064 类别">
          <a-select
            v-model:value="currentAsset.isoId"
            style="width: 100%"
            :fieldNames="{ label: 'isoName', value: 'isoId' }"
            :options="isoCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="行业类型">
          <a-select
            v-model:value="currentAsset.industryId"
            style="width: 100%"
            :fieldNames="{ label: 'industryName', value: 'industryId' }"
            :options="industryCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="生态类型">
          <a-select
            v-model:value="currentAsset.ecoId"
            style="width: 100%"
            :fieldNames="{ label: 'ecoName', value: 'ecoId' }"
            :options="ecoCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="碳资产描述">
          <a-textarea v-model:value="currentAsset.assetDescription" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
  import { AppstoreOutlined, MailOutlined } from '@ant-design/icons-vue';
  import { h, reactive, computed, ref, onMounted } from 'vue';
  import { assetManagement } from '/@/api/Carbon module/Carbon asset module/Carbon asset/assetManagement';
  import { smartSentry } from '/@/lib/smart-sentry';

  const carbonAssets = ref([]);

  const columns = [
    { title: '碳资产名称', dataIndex: 'assetName' },
    { title: '碳资产类别', dataIndex: 'caCategoryName' },
    { title: 'GHG Protocol 范围', dataIndex: 'ghgName' },
    { title: 'ISO 14064 类别', dataIndex: 'isoName' },
    { title: '行业类型', dataIndex: 'industryName' },
    { title: '生态类型', dataIndex: 'ecoName' },
    { title: '碳资产描述', dataIndex: 'assetDescription' },
    { title: '操作', dataIndex: 'action', key: 'action' },
  ];

  const isModalVisible = ref(false);
  const currentAsset = ref(null);
  // 打开增加碳资产的弹窗
  const addCarbonAsset = () => {
    currentAsset.value = {
      assetName: '',
      assetCategoryId: '',
      ghgId: '',
      isoId: '',
      industryId: '',
      ecoId: '',
      assetDescription: '',
    };
    isEdit.value = false;
    isModalVisible.value = true;
  };

  // 打开编辑碳资产的弹窗
  const isEdit = ref(false);
  const editCarbonAsset = (asset) => {
    isEdit.value = true;
    currentAsset.value = { ...asset };
    assetsCategories.value.forEach((item) => {
      if (item.caCategoryName == asset.caCategoryName) {
        currentAsset.value.assetCategoryId = item.caCategoryId;
      }
    });
    ghgCategories.value.forEach((item) => {
      if (item.ghgName == asset.ghgName) {
        currentAsset.value.ghgId = item.ghgId;
      }
    });
    isoCategories.value.forEach((item) => {
      if (item.isoName == asset.isoName) {
        currentAsset.value.isoId = item.isoId;
      }
    });
    industryCategories.value.forEach((item) => {
      if (item.industryName == asset.industryName) {
        currentAsset.value.industryId = item.industryId;
      }
    });
    ecoCategories.value.forEach((item) => {
      if (item.ecoName == asset.ecoName) {
        currentAsset.value.ecoId = item.ecoId;
      }
    });
    isModalVisible.value = true;
  };

  // 保存碳资产（新增或编辑）
  const saveCarbonAsset = async () => {
    if (currentAsset.value.assetName) {
      if (isEdit.value) {
        // 编辑已有资产
        try {
          await assetManagement.Update({ ...currentAsset.value });
          queryData();
        } catch (error) {
          console.log(error);
        }
      } else {
        // 新增资产
        try {
          await assetManagement.Add({ ...currentAsset.value });
          queryData();
        } catch (error) {
          console.log(error);
        }
      }
      isModalVisible.value = false;
    }
  };

  // 关闭弹窗
  const handleCancel = () => {
    isModalVisible.value = false;
  };

  // 菜单项目和状态管理

  function getItem(label, key, icon, children) {
    return { key, icon, children, label };
  }

  const items = reactive([
    getItem('能源类碳资产', 'sub1', () => h(MailOutlined), [getItem('可再生能源发电', '1-1'), getItem('余热余压利用', '1-2')]),
    getItem('工业过程类碳资产', 'sub2', () => h(AppstoreOutlined), [getItem('工艺流程优化', '2-1'), getItem('其他...', '2-2')]),
  ]);

  const state = reactive({
    rootSubmenuKeys: ['sub1', 'sub2'],
    openKeys: ['sub1'],
    selectedKeys: [],
  });

  const onOpenChange = (openKeys) => {
    const latestOpenKey = openKeys.find((key) => state.openKeys.indexOf(key) === -1);
    if (state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      state.openKeys = openKeys;
    } else {
      state.openKeys = latestOpenKey ? [latestOpenKey] : [];
    }
  };

  const deleteCarbonAsset = async (asset) => {
    try {
      await assetManagement.Delete(asset.assetId);
      queryData();
    } catch (error) {
      console.log(error);
    }
  };

  // 查询碳资产列表
  const pagination = computed(() => ({
    total: total.value,
    pageSize: queryFormState.pageSize,
    current: queryFormState.pageNum,
    showTotal: (total) => `总共${total}项`,
  }));
  const queryFormState = reactive({
    pageNum: 1,
    pageSize: 10,
  });
  const tableLoading = ref(false);
  const total = ref(0); //总数
  const queryForm = reactive({ ...queryFormState });
  async function queryData() {
    tableLoading.value = true;
    try {
      queryForm.pageNum = queryFormState.pageNum; // 确保页码同步
      queryForm.pageSize = queryFormState.pageSize;
      let queryResult = await assetManagement.query(queryForm);
      carbonAssets.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
  const handleChange = (pagination, filters, sorter) => {
    queryFormState.pageNum = pagination.current; // 更新当前页
    queryFormState.pageSize = pagination.pageSize; // 更新页大小
    queryData();
  };

  // 碳资产类型
  const assetsCategories = ref([]);
  async function queryAssetsCategory() {
    let queryResult = await assetManagement.queryAssetsCategory({
      pageNum: 1,
      pageSize: 100,
    });
    assetsCategories.value = queryResult.data.list;
  }

  //GHG
  const ghgCategories = ref([]);
  async function queryGHG() {
    let queryResult = await assetManagement.queryGHG({
      pageNum: 1,
      pageSize: 100,
    });
    ghgCategories.value = queryResult.data.list;
  }

  // ISO
  const isoCategories = ref([]);
  async function queryISO() {
    let queryResult = await assetManagement.queryISO({
      pageNum: 1,
      pageSize: 100,
    });
    isoCategories.value = queryResult.data.list;
  }

  // 行业类型
  const industryCategories = ref([]);
  async function queryIndustry() {
    let queryResult = await assetManagement.queryIndustry({
      pageNum: 1,
      pageSize: 100,
    });
    industryCategories.value = queryResult.data.list;
  }

  // 生态类型
  const ecoCategories = ref([]);
  async function queryEco() {
    let queryResult = await assetManagement.queryEco({
      pageNum: 1,
      pageSize: 100,
    });
    ecoCategories.value = queryResult.data.list;
  }

  onMounted(() => {
    queryData();
    queryAssetsCategory();
    queryGHG();
    queryISO();
    queryIndustry();
    queryEco();
  });
</script>

<style scoped>
  .carbon-assets-container {
    display: flex;
    background-color: #f4f6f8;
    /* height: 100vh; */
  }

  .sidebar {
    width: 256px;
    color: #fff;
    padding: 16px;
    box-shadow: 2px 0 6px rgba(0, 0, 0, 0.1);
    border-right: 1px solid #d9d9d9;
    background-color: white;
    height: 85vh;
    display: table-cell;
  }

  .add-button {
    margin-bottom: 20px;
    background-color: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }

  .carbon-assets-table {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  .card {
    flex: 1;
    margin-left: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: auto;
  }
  .ant-table-thead > tr > th {
    background-color: #e6f7ff;
    color: #333;
  }

  .ant-table-tbody > tr:hover {
    background-color: #f5f5f5;
  }
</style>
